package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.execptiom.BusinessException;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.ICategoryService;
import com.itheima.service.IDishService;
import com.itheima.service.Impl.DishServiceImpl;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    ICategoryService categoryService;

    @Autowired
    IDishService dishService;

    //新增分类
    @PostMapping
    private R saveCategory(@RequestBody Category category, HttpServletRequest request){

        //调用方法
        categoryService.save(category);

        return R.success("新增分类成功");
    }

    /*
    * 查询全部并分页
    * */
    @GetMapping("/page")
    private R<Page> pageSelectAll(Long page, Long pageSize){
        Page Ipage = new Page<Category>(page, pageSize);

        //排序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);

        categoryService.page(Ipage,wrapper);

        return R.success(Ipage);
    }

    //删除分类
    @DeleteMapping
    private R deleteById(Long id){
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(wrapper);
        if (count1 > 0){
            //不能删除
            throw new BusinessException("该菜品有关联不能删除",0);
        }

        LambdaQueryWrapper<Setmeal> wrapper2 = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,id);
        int count2 = dishService.count(wrapper);
        if (count2 > 0){
            //不能删除
            throw new BusinessException("该套餐有关联不能删除",0);
        }


        categoryService.removeById(id);
        return R.success("删除成功");
    }

    //修改分类
    @PutMapping
    private R updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    //查询菜品分类列表
    @GetMapping("/list")
    private R selectDish(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());

        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
